﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DrawLine
{
    public class RandomLines : FrameworkElement
    {
        Random _rnd = new Random();

        Pen _pen;

        public int LineCount
        {
            get { return (int)GetValue(LineCountProperty); }
            set { SetValue(LineCountProperty, value); }
        }
        public static readonly DependencyProperty LineCountProperty =
            DependencyProperty.Register("LineCount", typeof(int), typeof(RandomLines), new PropertyMetadata(2048));

        public double LineThickness
        {
            get { return (double)GetValue(LineThicknessProperty); }
            set { SetValue(LineThicknessProperty, value); }
        }
        public static readonly DependencyProperty LineThicknessProperty =
            DependencyProperty.Register("LineThickness", typeof(double), typeof(RandomLines), 
            new PropertyMetadata(1.0,
                (d, e) => {
                    ((RandomLines)d).RefreshPen();
                }));

        public RandomLines()
        {
            RefreshPen();
        }

        private void RefreshPen()
        {
            _pen = new Pen(Brushes.Black, LineThickness);
            _pen.Freeze();
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            var size = DesiredSize;

            var count = LineCount;

            for(int idx=0; idx<count ; idx++)
            {
                var point1 = new Point(_rnd.NextDouble() * size.Width, _rnd.NextDouble() * size.Height);
                var point2 = new Point(_rnd.NextDouble() * size.Width, _rnd.NextDouble() * size.Height);

                drawingContext.DrawLine(_pen, point1, point2);
            }
        }
    }
}
